% [1] F. Plestan, Y. Shtessel, V. Brégeault, and A. Poznyak, 
% “New methodologies for adaptive sliding mode control,” 
% Int. J. Control, vol. 83, no. 9, pp. 1907–1919, Sep. 2010, doi: 10.1080/00207179.2010.501385.
% in section 3.1 First adaptive sliding mode control law
% main algorithms can be found in equation 13 14

%% initialize parameters
params=struct();
tfinal=8;
params.t=linspace(0,tfinal,200);
params.delta=rand(size(params.t));
params.k1bar=1;
params.k3bar=0.1;
params.tau=1;
params.mu=0.1;
initial=[1;0.1;0];
[dxdt0,s0]=rhs(0,initial,params);

%% run the simulation
opt=odeset("AbsTol",1e-4,"RelTol",1e-4,"OutputFcn","odeplot");
[t,x]=ode45(@(t,x)rhs(t,x,params),linspace(0,tfinal,1000),initial,opt);
s=repmat(s0,length(t),1);
for i=1:length(t)
    [dxdti,si]=rhs(t(i),x(i,:)',params);
    s(i)=si;
end
save adaptive_sign1.mat
%% plot result
figure;
nexttile;hold on;
plot(t,x(:,1));
nexttile;hold on;
plot(t,horzcat(s.k));
plot(t,x(:,3));
plot(params.t,params.delta)
legend(["k","\eta","\delta"])
exportgraphics(gcf,"adaptive_sign1.png")

%%
function [dxdt,s]=rhs(t,states,p)
    persistent k2bar
    s=struct();
    x=states(1);
    k=states(2);
    eta=states(3);
    doteta=0;
    dotk=0;
    
    if abs(x)<1e-2
        if isempty(k2bar)
            k2bar=k;
        end
        k=k2bar*abs(eta)+p.k3bar;
        doteta=1/p.tau*(sign(x)-eta);
    else
        dotk=p.k1bar*abs(x);
    end
    u=-k*sign(x);
    s.k=k;
    delta=interp1(p.t,p.delta,t);
    dxdt=[u+delta;dotk;doteta];
end